package com.sailorj.medical.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sailorj.medical.dao.Family_memberDAO;
import com.sailorj.medical.dao.Join_nhDao;
import com.sailorj.medical.domain.area.Area;
import com.sailorj.medical.domain.family.Family;
import com.sailorj.medical.domain.family_member.Family_member;
import com.sailorj.medical.domain.join_nh.Join_nh;
import com.sailorj.medical.exception.DbException;
import com.sailorj.medical.util.ExportExcel;
import com.sailorj.medical.util.MyTime;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Join_nhServlet extends BaseServlet {
	private static final Logger LOG = LogManager.getLogger(Join_nhServlet.class);
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String m = request.getParameter("m");// 动作类型参数
		if ("list".equals(m)) {
			process(request, response, "/page/join_nh/join_nh_list.jsp");
		} else if ("input".equals(m)) {
			process(request, response, "/page/join_nh/join_nh_add.jsp");
		} else if ("get".equals(m)) {
			process(request, response, "/page/join_nh/join_nh_edit.jsp");
		} else if ("add".equals(m)) {
			add(request, response);
		} else if ("edit".equals(m)) {
			this.edit(request, response);
		} else if ("del".equals(m)) {
			this.del(request, response);
		} else if ("in".equals(m)) {
//			process(request, response, "/page/join_nh/join_findadd.jsp");
			process(request, response, "/page/join_nh/join-nh_add.jsp");
		} else if ("find".equals(m)) {
			this.find(request, response);
		} else if ("print".equals(m)) {
			this.findByJoin_invoice_code(request, response);
		} else if ("findByLike".equals(m)) {
			this.findByLike(request, response);
			process(request, response, "/page/join_nh/join_nh_findList.jsp");
		} else if ("excel".equals(m)) {
			this.outExcel(request, response);
			process(request, response, "/page/join_nh/join_nh_list.jsp");
		} else if ("outexcel".equals(m)) {
			this.gotoexcel(request, response);
			this.outExcel(request, response);
			process(request, response, "/page/join_nh/join_nh_list.jsp");
			return;
		} else if ("sign".equals(m)) {
			this.sign(request, response);
			process(request, response, "/page/join_nh/join_nh_list.jsp");
		}
	}
		//参合登记
	private void sign(HttpServletRequest request, HttpServletResponse response) {
		String join_nh_code = request.getParameter("join_nh_code");
		// 接收页面传递过来的参数
		Join_nh join_nh = new Join_nh();
		// 调用保存的方法
		try {
			join_nh.add(join_nh_code,request);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	List<Join_nh> list1 = new ArrayList<Join_nh>();

	private String gotoexcel(HttpServletRequest rs, HttpServletResponse resp) throws ServletException, IOException {
		this.findByLike(rs, resp);
		return null;
	}

	private void outExcel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {

			List<HashMap<String, Object>> listMap = new ArrayList<>();
			HashMap<String, Object> dataMap = new HashMap<>();

			for (int i = 0; i < list1.size(); i++) {
				dataMap.put("join_nh_code", list1.get(i).getJoin_nh_code());
				dataMap.put("family_id", list1.get(i).getFamily().getFamilyname());
				dataMap.put("join_id_card", list1.get(i).getJoin_id_card());
				dataMap.put("join_invoice_code", list1.get(i).getJoin_invoice_code());

				dataMap.put("join_time", list1.get(i).getJoin_time());
				dataMap.put("join_year", list1.get(i).getJoin_year());
				dataMap.put("money", list1.get(i).getMoney());
				dataMap.put("area", list1.get(i).getArea().getAreaname());

				dataMap.put("user_id", list1.get(i).getUser_id());
				listMap.add(dataMap);// 有BUG，会覆盖已有的数据
				LOG.info("dataMap=="+dataMap.toString());
			}

			String title = "参合登记记录";
			String[] rowsName = new String[] { "序号", "参合登记编码", "家庭编号", "参合人身份证号", "参合发票编号", "登记时间", "参合年份", "缴费金额",
					"行政区域", "登记员" };
			List<Object[]> dataList = new ArrayList<Object[]>();
			Object[] objs = null;
			for (int i = 0; i < listMap.size(); i++) {
				HashMap<String, Object> data = listMap.get(i);
				objs = new Object[rowsName.length];
				objs[0] = i;
				objs[1] = data.get("join_nh_code");
				objs[2] = data.get("family_id");
				objs[3] = data.get("join_id_card");
				objs[4] = data.get("join_invoice_code");

				objs[5] = data.get("join_time");
				objs[6] = data.get("join_year");
				objs[7] = data.get("money");
				objs[8] = data.get("area");

				objs[9] = data.get("user_id");
				dataList.add(objs);
				LOG.info("objs=="+objs.toString());
			}
			ExportExcel ex = new ExportExcel(title, rowsName, dataList);
			ex.export(resp);
		} catch (Exception e) {
			// TODO: handle exception
			LOG.info("e===="+e);
		}
	}


	private void find(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		LOG.info("来到了find()");
		// 1：接收参数
		String familycode = req.getParameter("familycode");
		LOG.info("familycode==" + familycode);
		// 2:构造新慢病信息对象
		Family_memberDAO model = new Family_memberDAO();
		Join_nhDao nhDao = new Join_nhDao();
		List<Family_member> list = new ArrayList<Family_member>();

		try {

			List<Family_member> list1 = model.findFamilyList(familycode);
			if (list1 != null) {

				for (int i = 0; i < list1.size(); i++) {

					List<Join_nh> nhList = nhDao.findJoin_nhList(list1.get(i).getIDcard());
					list1.get(i).setCh_year("未参合");
					if (nhList != null && !nhList.isEmpty()) {
						list1.get(i).setCh_year("已参合");
					}
					list.add(list1.get(i));
				}
			}
			for (Family_member m :list ) {
			    LOG.info("找出的getUserid="+m.getMembername()+m.getCh_year());
			}
			req.setAttribute("list", list);

			LOG.info(list);
			process(req, resp, "/page/join_nh/join-nh_add.jsp");
		} catch (Exception e) {
			error(req, resp);
			LOG.info(e);
		}

	}

	public void findByJoin_invoice_code(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<Join_nh> menberList = new ArrayList<Join_nh>();
		HttpSession session = req.getSession();
		Join_nhDao join_nhDao = new Join_nhDao();
		String join_invoice_code = session.getAttribute("join_invoice_code").toString();
		// String join_invoice_code = "6532565833783181312";
		try {
			List<Join_nh> list = join_nhDao.findByKeyValue("join_invoice_code", join_invoice_code);
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setFamily_id(list.get(i).getFamily().getFamilyname());
				// list.get(i).set
				menberList.add(list.get(i));
			}
			req.setAttribute("list", menberList);
			req.setAttribute("join_invoice_code", menberList.get(0).getJoin_invoice_code());
			req.setAttribute("family_name", menberList.get(0).getFamily().getFamilyname());
			req.setAttribute("user_id", menberList.get(0).getUser_id());
			req.setAttribute("menber", menberList.size());
			int size = Integer.valueOf(menberList.size()).intValue();
			int money = Integer.valueOf(menberList.get(0).getMoney()).intValue();
			money = money * size;
			req.setAttribute("money", money);
			req.setAttribute("areaname", menberList.get(0).getArea().getAreaname());

			session.removeAttribute("join_invoice_code");// 清除session
			process(req, resp, "/page/join_nh/print.jsp");
		} catch (DbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void add(HttpServletRequest rs, HttpServletResponse response) throws ServletException, IOException {
		// 接收页面传递过来的参数
		String list = rs.getParameter("familyarr");
		Join_nh join_nh = new Join_nh();
		// 调用保存的方法
		try {
			join_nh.addJoin_nh(list, rs);
			this.findByJoin_invoice_code(rs, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void findByLike(HttpServletRequest rs, HttpServletResponse resp) throws ServletException, IOException {
		try {
			list1.clear();
			// 定义一个sb来接收模糊查询的sql
			StringBuffer sb = new StringBuffer(1024);
			Join_nhDao model = new Join_nhDao();

			String family_id = rs.getParameter("family_id");
			String join_year = rs.getParameter("join_year");
			String areacode = rs.getParameter("areacode");
			String startTime = rs.getParameter("startTime");
			String endTime = rs.getParameter("endTime");

			if (family_id != null && !"".equals(family_id)) {
				sb.append(" and family_id = '" + family_id + "'");
			}
			if (join_year != null && !"".equals(join_year)) {
				sb.append(" and join_year = '" + join_year + "'");
			}
			if (areacode != null && !"".equals(areacode)) {
				sb.append(" and areacode = '" + areacode + "'");
			}
			if (startTime != null && !"".equals(startTime) && endTime != null && !"".equals(endTime)) {
				sb.append(" and join_time between '" + startTime + "' AND '" + endTime + "' ");
			} else {
				if (startTime != null && !"".equals(startTime)) {
					sb.append(" and join_time between '" + startTime + "' AND '" + MyTime.getNowForTimestamp() + "' ");
				} else if (endTime != null && !"".equals(endTime)) {
					sb.append(" and join_time between '" + MyTime.getNowForTimestamp() + "' AND '" + endTime + "' ");
				}
			}

			List<Join_nh> list = model.findByLike(sb.toString());

			list1.addAll(list);

			rs.setAttribute("list", list);

		} catch (DbException e) {
			error(rs, resp);
		}
	}

	private void edit(HttpServletRequest rs, HttpServletResponse resp) throws ServletException, IOException {

		// 1：接收参数

		String familycode = rs.getParameter("familycode");
		String familyname = rs.getParameter("familyname");
		String IDcard = rs.getParameter("IDcard");
		String familyaddr = rs.getParameter("familyaddr");
		String familynumber = rs.getParameter("familynumber");
		String familystate = rs.getParameter("familystate");
		String areacode = rs.getParameter("areacode");
		String familyteam = rs.getParameter("familyteam");

		try {
			// 2:构造新慢病信息对象
			Area area = new Area(areacode);
			Family model = new Family(familycode, familyname, IDcard, familyaddr, familynumber, familystate, area,
					familyteam);
			// 3：调用保存的方法
			model.edit();
			process(rs, resp, "/page/join_nh/join_nh_list.jsp");
		} catch (Exception e) {
			error(rs, resp);
		}

	}

	private void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 1：接收参数
		String familycode = req.getParameter("id");

		// 2:构造新慢病信息对象
		Family model = new Family();
		try {
			model.del(familycode);
			process(req, resp, "/page/join_nh/join_nh_list.jsp");
		} catch (Exception e) {
			error(req, resp);
		}

	}

}
